package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ReservationDTO;
import com.sky.entity.BookingOrder;
import com.sky.entity.MeetingRoom;
import com.sky.entity.Payment;
import com.sky.mapper.BookingOrderMapper;
import com.sky.mapper.MeetingRoomMapper;
import com.sky.mapper.PaymentMapper;
import com.sky.service.MeetingRoomService;
import com.sky.service.ReservationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;

import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReservationServiceImpl implements ReservationService {

    @Autowired
    private BookingOrderMapper bookingOrderMapper;
    @Autowired
    private MeetingRoomMapper meetingRoomMapper;
    @Autowired
    private PaymentMapper paymentMapper;


    /**
     * 生成订单
     *
     * @param reservationDTO
     */
    @Override
    @Transactional
    public String bookRoom(ReservationDTO reservationDTO) {
        //判断会不会冲突
        List<MeetingRoom> meetingRoomList=new ArrayList<>();
        meetingRoomList.add(meetingRoomMapper.getById(reservationDTO.getMeetingRoomId()));
        // 获取会议室ID列表
        List<Long> roomIds = meetingRoomList.stream()
                .map(MeetingRoom::getId)
                .collect(Collectors.toList());

        System.out.println(roomIds);
        // 查询在指定时间段内有已支付订单的会议室ID
        List<Long> bookedRoomIds = bookingOrderMapper.getPaidBookedRoomIds(
                reservationDTO.getBooking_start_time(),
                reservationDTO.getBooking_end_time(),
                roomIds
        );

        System.out.println(bookedRoomIds);
        for( Long id:bookedRoomIds){
            if(id==reservationDTO.getMeetingRoomId()){
                System.out.println("会议室时间冲突");
                return "不好意思，您预定的会议室时间段与其他客户冲突";
            }
        }



        //会议室修改为锁定状态
        meetingRoomMapper.updateStatusToLocking(reservationDTO.getMeetingRoomId());

        //生成订单
        MeetingRoom meetingRoom = meetingRoomMapper.getById(reservationDTO.getMeetingRoomId());
        LocalDateTime start = reservationDTO.getBooking_start_time();
        LocalDateTime end = reservationDTO.getBooking_end_time();
        long hours = calculateHours(start, end);
        System.out.println("总时间是" + hours);
        System.out.println("单价是" + meetingRoom.getPricePerHour());

        BookingOrder bookingOrder = BookingOrder.builder()
                .meetingRoomId(meetingRoom.getId())
                .userId(BaseContext.getCurrentId())
                .bookingStartTime(reservationDTO.getBooking_start_time())
                .bookingEndTime(reservationDTO.getBooking_end_time())
                .bookingDate(reservationDTO.getBooking_date())
                .pricePerHour(meetingRoom.getPricePerHour())
                .hoursBooked(hours)
                .totalPrice(hours * meetingRoom.getPricePerHour())
                .paymentStatus("未支付")
                .createtime(LocalDateTime.now())
                .updatetime(LocalDateTime.now())
                .build();
        System.out.println(bookingOrder);
        bookingOrderMapper.insert(bookingOrder);

        //生成支付数据
        Payment payment=Payment.builder()
                .userId(BaseContext.getCurrentId())
                .orderId(bookingOrder.getOrderId())
                .paymentMethod("微信支付")
                .paymentStatus("未支付")
                .build();
        System.out.println(payment);
        paymentMapper.insert(payment);
        return "预定成功";
    }

    //计算时间函数
    private long calculateHours(LocalDateTime start, LocalDateTime end) {
        if (start.isAfter(end)) {
            throw new IllegalArgumentException("开始时间必须早于结束时间");
        }
        // 计算两个时间之间的小时差，向上取整
        long hours = start.until(end, ChronoUnit.HOURS);
        // 如果有额外的分钟或秒，增加一个小时
        if (start.plusHours(hours).isBefore(end)) {
            hours++;
        }
        return hours;
    }



}
